import BScroll from '@better-scroll/core'
import ObserveDOM from '@better-scroll/observe-dom'

BScroll.use(ObserveDOM)

export default function useScroll(wrapperRef, options, emit) {
  const scroll = ref(null)
  const EVENT_NAME = 'scroll'

  onMounted(() => {
    scroll.value = new BScroll(wrapperRef.value, {
      observeDOM: true,
      ...options,
    })
    if (options.probeType > 0) {
      scroll.value.on(EVENT_NAME, (pos) => {
        emit(EVENT_NAME, pos)
      })
    }
  })

  onUnmounted(() => scroll.value.destroy())

  onActivated(() => {
    const instance = scroll.value
    instance.enable()
    instance.refresh()
  })

  onDeactivated(() => scroll.value.disable())

  return scroll
}
